package myUser;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.NamingException;

import onlineAccessManagement.DBLib;

public class UserDao {
	Connection conn;
	String sql;
	PreparedStatement ps;
	//连接数据库
	public UserDao() throws NamingException, SQLException {
		conn=DBLib.getconn();
		sql="use Visitor";
		ps=conn.prepareStatement(sql);
		ps.executeUpdate();
	}
	
	//用户名和密码的对应判断
	public int getUserid(User u) throws SQLException, NamingException {
		if(conn.isClosed()) {
			conn=DBLib.getconn();
		}
		
		sql="select id from users where username=? and pwd=?";
		ps=conn.prepareStatement(sql);
		ps.setString(1, u.getUserName());
		ps.setString(2, u.getPassword());	
		ResultSet rs=ps.executeQuery();
		int id=0;
		if(rs.next()) {
			id=rs.getInt(1);	//如果数据库中有匹配的id，则返回
		}
		conn.close();
		return id;
	}
	
	//通过id找到用户名
	public String getNamebyId(int id) throws NamingException, SQLException {
		if(conn.isClosed()) {
			conn=DBLib.getconn();
		}
		sql="select username from users where id=?";
		ps=conn.prepareStatement(sql);
		ps.setInt(1, id);
		ResultSet rs=ps.executeQuery();
		String name="";
		if(rs.next()) {
		name=rs.getString(1);
		}
		conn.close();
		return name;
	}
	
	//通过名字获得id
	public int getIdbyName(String name) throws SQLException, NamingException {
		if(conn.isClosed()) {
			conn=DBLib.getconn();
		}
		sql="select id from users where username=?";
		ps=conn.prepareStatement(sql);
		ps.setString(1, name);
		ResultSet rs=ps.executeQuery();
		int id=0;
		while(rs.next()) {
			id=rs.getInt(1);
		}
		conn.close();
		return id;
	}
}
